<template>
	<el-form ref="form" :model="form" label-width="80px" @submit.prevent="onSubmit" style="width:100%;min-width:300px;">
<!--		<el-form-item label="订单编号">-->
<!--			<el-input v-model="form.orderId" :disabled="true"></el-input>-->
<!--		</el-form-item>-->
		<!--<el-form-item label="商家shopuuid">-->
			<!--<el-input v-model="form.shopuuid"></el-input>-->
		<!--</el-form-item>-->
		<el-form-item label="分销商" prop="useruuid">
			<el-select v-model="form.uid" placeholder="请选择分销商"
					   @change="userChange">
				<el-option value="0" label="全部">全部</el-option>
				<el-option
						v-for="item in users"
						:key="item.user.useruuid"
						:label="item.user.username"
						:value="item.user.useruuid">
				</el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="业务类型" prop="busuuid">
			<el-select v-model="form.busCode" clearable placeholder="请选择业务类型">
				<el-option value="0" label="全部">全部</el-option>
				<el-option
						v-for="item in bus"
						:key="item.busuuid"
						:label="item.busname"
						:value="item.busCode">
				</el-option>
			</el-select>
		</el-form-item>

		<el-form-item label="账号余额">
			<span >{{form.downshopbalance}}</span>
		</el-form-item>

<!--		<el-form-item label="产品名称" prop="productuuid">-->
<!--			<el-select v-model="form.pid" placeholder="请选择产品" @change="productChange">-->
<!--				<el-option value="0" label="全部">全部</el-option>-->
<!--				<el-option-->
<!--						v-for="item in products"-->
<!--						:key="item.downprouuid"-->
<!--						:label="item.productName"-->
<!--						:value="item.downprouuid">-->
<!--				</el-option>-->
<!--			</el-select>-->
<!--		</el-form-item>-->
<!--		<el-form-item label="充值金额">-->
<!--			<el-input v-model="form.amount" :disabled="true"></el-input>-->
<!--		</el-form-item>-->

		<el-form-item label="充值号码">
			<el-input  type="textarea" v-model="form.phone" :rows="15"
			placeholder="
			批量充值时格式为:号码+空格+面值
			18011112222 100
			18900002222 50
			15922223333 30"  ></el-input>
		</el-form-item>
		<el-form-item label="">
			<span >当日已提交订单数:{{orderNum}}笔,当日合计面值:{{orderMoney}}元</span>
		</el-form-item>
<!--		<el-form-item label="回调地址">-->
<!--			<el-input v-model="form.notify"></el-input>-->
<!--		</el-form-item>-->
<!--		<el-form-item label="时间戳">-->
<!--			<el-input v-model="form.ts"></el-input>-->
<!--		</el-form-item>-->
		<!--<el-form-item label="key">-->
			<!--<el-input v-model="form.key"></el-input>-->
		<!--</el-form-item>-->
<!--		<el-form-item label="SIGN">-->
<!--			<el-input v-model="form.sign"></el-input>-->
<!--		</el-form-item>-->
		<el-form-item label="批次号:">
			<el-input clearable="true"  v-model="form.batchNumber"></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" v-on:click="onrestBatch">批量充值</el-button>
		</el-form-item>
	</el-form>
</template>

<script>
	import {
		findAllDownShopInfo,
		getConfig,
		restBatch,
		findUserManualOrder, findAllBus
	} from '../../api/api';
	import moment from "moment";
    var crypto = require('crypto');

	export default {
		data() {
			return {
				form: {
                    orderId: 'yidongpingtai'+new Date().getTime(),
                    uid: '0',
                    amount: '',
					downshopbalance:'',
					busCode:'',
                    pid: '',
                    phone: '',
                    notify: '',
                    key: '',
                    sign:'',
					batchNumber:'',
                    ts:new Date().getTime()
				},
				bus: [],
                users:[],
                products:[],
				orderNum:0,
				orderMoney:0
			}
		},
		methods: {
			findAllBus: function () {
				let para = {useruuid: ''};
				findAllBus(para).then(datas => {
					let {message, code, data} = datas;
					if (code !== "0") {
						this.$message({
							message: message,
							type: 'error'
						});
					} else {
						this.bus = data;
					}
				});
			},
			onrestBatch:function(){
				if(this.form.uid == "0" ) {
					this.$message({
						message: "请选择分销商",
						type: 'error'
					});
					return;
				}
				if(this.form.busCode == "0" || this.form.busCode == "" ){
					this.$message({
						message: "请选择业务类型",
						type: 'error'
					});
					return;
				}
				console.log(this.form.busCode)
				const phones = this.form.phone.split("\n");
				const kongge = phones.find(item =>{ return item == ""});
				console.log(kongge)
				if(!kongge && kongge != undefined){
					this.$message({
						message: "格式错误,请仔细检查,如空格",
						type: 'error'
					});
				}else{
					if(phones.length == 0 || phones[0] == ""){
						this.$message({
							message: "号码不能为空",
							type: 'error'
						});
					}else {
						if(this.form.uid == "0" ){
							this.$message({
								message: "请选择分销商",
								type: 'error'
							});
						}else{
							let orderMoney = 0;
							phones.forEach(item => {
								const ph = item.indexOf(" ") != -1 ? item.split(" ") : item.split("	");
								orderMoney += parseInt(ph[1]);
							});
							console.log("orderMoney:",orderMoney)

							this.$confirm('确认批量提交订单吗？\n当前充值中订单数:'+phones.length+"\n当前充值总面值:"+orderMoney+" 元", '提示', {}).then(() => {
								var orders = [];
								if(phones){
									for(var i = 0 ; i < phones.length; i++){
										var order = new Object();
										order.orderId = Math.random().toString(36).substr(2)+new Date().getTime();
										order.uid = this.form.uid;
										const ph = phones[i].indexOf(" ") != -1 ? phones[i].split(" ") : phones[i].split("	");
										if(!ph[0] || !ph[1]){
											console.log("异常号码:",phones[i])
											continue;
										}
										order.busCode = this.form.busCode;
										order.phone = ph[0];
										order.money = ph[1];
										order.notify = this.form.notify;
										order.ts = this.form.ts;
										order.statusremark = this.form.batchNumber;
										orders.push(order)
									}
								}
								const param = {
									orders : orders,
									useruuid: this.form.uid,
									orderMoney:orderMoney,
									orderNum:phones.length
								}
								restBatch(JSON.stringify(param)).then( datas => {
									let { message, code, data } = datas;
									if (code !== "0") {
										this.$message({
											message: message,
											type: 'error'
										});
									}else{
										this.$message({
											message: "提交成功",
											type: 'info'
										});
									}
									this.form.orderId = 'weiliupingtai'+new Date().getTime();
									this.form.ts = new Date().getTime();
									this.form.phone = "";
								});
							});
						}
					}
				}
			}
			,findAllDownShopInfo: function () {
                let para = {useruuid: JSON.parse(sessionStorage.getItem("user")).useruuid};
                findAllDownShopInfo(para).then(datas => {
                    let {message, code, data} = datas;
                    if (code !== "0") {
                        this.$message({
                            message: message,
                            type: 'error'
                        });
                    } else {
                        this.users = data;
                    }
                });
            },getConfig(){
                let para = {useruuid: JSON.parse(sessionStorage.getItem("user")).useruuid};
                getConfig(para).then(datas => {
                    let {message, code, data} = datas;
                    if (code !== "0") {
                        this.$message({
                            message: message,
                            type: 'error'
                        });
                    } else {
                        this.form.orderId = data.testorderprefix+new Date().getTime();
                        this.form.notify = data.testcallbackurl;
                    }
                });
			},
			userChange: function (shopuuid) {
				if(this.users){
					const result = this.users.find(item => {return shopuuid == item.user.useruuid});
					if(result){
						this.form.downshopbalance = result.downshopbalance+" 元";
					}
				}
                let para = {useruuid: this.form.uid};
                findUserManualOrder(para).then(datas => {
                    let {message, code, data} = datas;
                    if (code !== "0") {
                        this.$message({
                            message: message,
                            type: 'error'
                        });
                    } else {
                    	this.orderMoney = data.orderMoney;
						this.orderNum = data.orderNum
                    }
                });
                // findDownShopInfoKey(para).then(datas => {
                //     let {message, code, data} = datas;
                //     if (code !== "0") {
                //         this.$message({
                //             message: message,
                //             type: 'error'
                //         });
                //     } else {
                //        this.form.key = data;
                //     }
                // });
			},productChange:function(productuuid){
				for(var i = 0 ; i < this.products.length ; i++){
				    if(this.products[i].downprouuid == productuuid){
                        this.form.amount = this.products[i].price;
					}
				}
			},
			signMethod(){
                var md5 = crypto.createHash('md5');
                var string = "notify="+this.form.notify+"&orderId="+this.form.orderId+"&phone="+this.form.phone+"&pid="+this.form.pid+"&ts="+this.form.ts+"&uid="+this.form.uid+"&key="+this.form.key;
				this.form.sign =  md5.update(string).digest('hex');
			}
		},mounted() {
			this.findAllBus();
            this.findAllDownShopInfo();
            this.getConfig();
            this.form.batchNumber = moment(new Date(),"YYYY-MM-DD HH:mm:ss").format('YYYYMMDDHHMMSS');
        }
	}

</script>
